<template>
  <div>
    <div class="inner">
      <template v-for="item in imgsArr_c">
        <div
          v-if="item.thumb"
          class="img-box default-card-animation demo-upload-list"
          :style="{
            width: imgWidth + 'px',
            height: item._height + 'px',
            position: 'absolute',
          }"
          ref="imgBox"
        >
          <img
            :data-src="item.thumb"
            v-lazy="item.thumb"
            width="100%"
            height="100%"
            @click="clickbigimg(item)"
          />
          <div class="demo-upload-list-cover" @click="handleRemove(item)">
            删除
          </div>
        </div>
      </template>
      <div
        v-if="showLast"
        :style="{
          position: 'absolute',
          color: '#999',
          left: 0,
          right: 0,
          textAlign: 'center',
          paddingBottom: '10px',
          top: `${top}`,
        }"
      >
        被你看完了！
      </div>
    </div>
    <Modal v-model="pigimgmodel" title="查看大图" :draggable="true" footer-hide>
      <img :src="src" style="width: 100%" />
    </Modal>
  </div>
</template>
<script>
import { imageDel } from "@/api/hqapi";
export default {
  name: "waterfall",
  props: ["imgList", "viewHeight", "patientId", "showLast"],
  data() {
    return {
      imgBoxEls: "",
      imgsArr_c: [],
      loadedCount: 0,
      beginIndex: 0,
      colNum: 3,
      colWidth: 298,
      imgWidth: 298,
      colsHeightArr: [],
      pigimgmodel: false,
      src: "",
      top: 0,
    };
  },

  watch: {
    imgList(newVal, oldVal) {
      this.loadedCount = 0;
      this.imgsArr = this.imgList;
      this.beginIndex = 0;
      this.preLoad();
    },
  },
  methods: {
    clickbigimg(data) {
      if (data.thumb) {
        this.src = data.file_url ? data.file_url : data.thumb;
        this.doesImageExist(this.src).then((res) => {
          if (res) {
            this.pigimgmodel = true;
          } else {
            this.$Message.error("图片不存在，请手动同步！");
          }
        });
      }
    },
    doesImageExist(url) {
      return new Promise(function(resolve) {
        var img = new Image();
        img.onload = function() {
          resolve(true); // 图片存在
        };
        img.onerror = function() {
          resolve(false); // 图片不存在
        };
        img.src = url;
      });
    },
    handleRemove(data) {
      this.$Modal.confirm({
        title: "删除提示",
        content:
          "删除后将不在病历图中展示，可在微信聊天中再次添加或手动上传进来?",
        onOk: () => {
          imageDel({ id: this.patientId, img_id: data.id }).then((res) => {
            this.$Message.warning("删除成功！");
            this.$emit("refresh");
          });
        },
      });
    },
    preLoad() {
      // forEach 无法通过 item 直接修改数组元素，需用数组下标修改
      if (this.imgsArr.length == 0) {
        this.preloaded();
      }
      this.imgsArr.forEach((item, index) => {
        // if (index < this.loadedCount) return;
        // 无图则把高度设置为0
        if (!item.thumb) {
          // 图片的高度
          this.imgsArr[index]._height = "0";
          ++this.loadedCount;
          // 当前图片都与处理完，则加载图片
          if (this.imgsArr.length === this.loadedCount) {
            this.preloaded();
          }
        } else {
          let img = new Image();
          img.src = item.thumb;
          img.onload = img.onerror = (e) => {
            // 若加载失败则设置图片高度与宽度一致，加载成功则动态计算图片高度

            this.imgsArr[index]._height =
              e.type === "load"
                ? Math.round(this.imgWidth * (img.height / img.width))
                : this.imgWidth;
            if (e.type === "error") {
              this.imgsArr[index]._error = true;
            }
            ++this.loadedCount;
            // 当前图片都与处理完，则加载图片
            if (this.imgsArr.length === this.loadedCount) {
              this.preloaded();
            }
          };
        }
      });
    },
    preloaded() {
      // 开始渲染
      this.imgsArr_c = [].concat(this.imgsArr);
      this.$nextTick(() => {
        // 对每个元素进行排列
        this.waterfall();
      });
    },
    waterfall() {
      // 选择所有图片
      this.imgBoxEls = this.$refs["imgBox"];
      // 若没图片，则返回
      if (!this.imgBoxEls) return;
      let top, left, height;
      // 开始排列的坐标，若为0则重头排列，colsHeightArr 数组保存的是当前每一列的高度
      if (this.beginIndex === 0) this.colsHeightArr = [];
      for (let i = this.beginIndex; i < this.imgBoxEls.length; ++i) {
        if (!this.imgBoxEls[i]) return;
        // 当前图片的高度
        height = this.imgBoxEls[i].offsetHeight;
        // 第一行，则直接按顺序排列
        if (i < this.colNum) {
          this.colsHeightArr.push(height);
          top = 0;
          // colWidth 为列宽，等于图片宽度加 div 左右的padding，colWidth = imgWdith + 2 * padding
          left = i * this.colWidth;
        } else {
          // 找到当前最低的高度和其索引
          let minHeight = Math.min.apply(null, this.colsHeightArr);
          let minIdx = this.colsHeightArr.indexOf(minHeight);
          // 当前图片的 top，即当前图片应所在的高度
          top = minHeight;
          // 当前图片的 left，即当前图片应该排到目前高度最低那一列下面
          left = minIdx * this.colWidth;
          // 更新第 minIdx 列的高度
          this.colsHeightArr[minIdx] += height;
        }
        // 设置 img-box 位置
        this.imgBoxEls[i].style.top = top + "px";
        this.imgBoxEls[i].style.left = left + "px";
        // 当前图片在窗口内，则加载，这是用于后面的图片懒加载。viewHeight 为窗口高度
        // let imgEl = this.imgBoxEls[i].children[0];
        // imgEl.src = imgEl.getAttribute("data-src");
        // imgEl.style.opacity = 1;
        // imgEl.style.transform = "scale(1)";
        if (i == this.imgBoxEls.length - 1) {
          this.top = top + height + 50 + "px";
        }
      }
      // 排列完之后，之后新增图片从这个索引开始预加载图片和排列，之前排列的图片无需在处理
      this.beginIndex = this.imgBoxEls.length;
    },
  },
};
</script>
<style scoped>
.inner {
  position: relative;
  /* overflow: auto; */
  height: 100%;
}
.img-box {
  padding: 10px 10px 0 0;
  cursor: pointer;
}
.demo-upload-list {
  position: relative;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  bottom: 0;
  left: 0;
  right: 10px;
  text-align: center;
  line-height: 40px;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover {
  color: #fff;
  font-size: 16px;
  cursor: pointer;
  margin: 0 2px;
}
img[lazy="loading"] {
  position: absolute;
  width: 50px !important;
  height: 50px !important;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
</style>
